<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="white-normal-box">
      <el-form-item label="机器编码" prop="machine">
        <el-input
          v-model="queryParams.machine"
          placeholder="请输入机器编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开通时间" prop="kaishi">
        <el-date-picker clearable
          v-model="queryParams.kaishi"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开通时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="jieshu">
        <el-date-picker clearable
          v-model="queryParams.jieshu"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入所属人"
          clearable
          @change="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="当前状态">
          <el-option :key="0" label="离线" :value="0" />
          <el-option :key="1" label="在线" :value="1" />
          <el-option :key="2" label="停止" :value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="金币总数量" prop="gold">
        <el-input
          v-model="queryParams.gold"
          placeholder="请输入金币总数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="每天金币数量" prop="goldDay">
        <el-input
          v-model="queryParams.goldDay"
          placeholder="请输入每天金币数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="white-normal-box">
      <el-row :gutter="10" class="mb20">
        <!-- <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:machine:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:machine:edit']"
          >修改</el-button>
        </el-col> -->
        <el-col :span="1.5">
          <!-- <el-tooltip class="item" effect="dark" content="存在勾选只修改勾选数据项，未勾选则必须搜索出某个用户的机器" placement="top"> -->
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="!((!multiple || (queryParams.userName && String(queryParams.userName || '').length !== 0)) && machineList && machineList.length !== 0)"
            @click="handleUpdateStatus"
            v-hasPermi="['system:machine:edit']"
          >设置机器状态</el-button>
          <!-- </el-tooltip> -->
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:machine:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:machine:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="machineList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="主键id" align="center" prop="id" /> -->
        <el-table-column label="机器编码" align="center" prop="machine" width="180" />
        <el-table-column label="所属人" align="center" prop="userName" width="120" />
        <el-table-column label="开通时间" align="center" prop="kaishi" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.kaishi, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="jieshu" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.jieshu, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金币总数量" align="center" prop="gold" min-width="100" />
        <el-table-column label="当前状态" align="center" prop="state">
          <template slot-scope="scope">
            <span>{{ ['离线', '在线', '停止'][scope.row.state || 0] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="每天金币数量" align="center" prop="goldDay" min-width="120" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:machine:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:machine:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改机器对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="机器编码" prop="machine">
          <el-input v-model="form.machine" placeholder="请输入机器编码" />
        </el-form-item>
        <el-form-item label="开通时间" prop="kaishi">
          <el-date-picker clearable
            v-model="form.kaishi"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择开通时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="jieshu">
          <el-date-picker clearable
            v-model="form.jieshu"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="金币总数量" prop="gold">
          <el-input v-model="form.gold" placeholder="请输入金币总数量" />
        </el-form-item>
        <el-form-item label="每天金币数量" prop="goldDay">
          <el-input v-model="form.goldDay" placeholder="请输入每天金币数量" />
        </el-form-item>
        <el-form-item label="当前状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio label="0">离线</el-radio>
            <el-radio label="1">在线</el-radio>
            <el-radio label="2">停止</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <el-dialog title="批量修改机器状态" :visible.sync="openState" width="500px" append-to-body>
      <el-form ref="formState" :model="formState" :rules="rulesState" label-width="100px">
        <el-form-item label="修改范围">{{ formState.userId ? `修改用户 “${formState.userName}” 的所有机器` : '修改当前勾选的机器' }}</el-form-item>
        <el-form-item label="当前状态" prop="state">
          <el-radio-group v-model="formState.state">
            <el-radio label="0">离线</el-radio>
            <el-radio label="1">在线</el-radio>
            <el-radio label="2">停止</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormState">确 定</el-button>
        <el-button @click="cancelState">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMachine, getMachine, delMachine, addMachine, updateMachine, updateMachineState } from "@/api/system/machine";

export default {
  name: "Machine",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机器表格数据
      machineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machine: null,
        kaishi: null,
        jieshu: null,
        userName: null,
        gold: null,
        state: null,
        goldDay: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 批量修改机器状态
      openState: false,
      formState: {},
      rulesState: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询机器列表 */
    getList() {
      this.loading = true;
      listMachine(this.queryParams).then(response => {
        this.machineList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        machine: null,
        kaishi: null,
        jieshu: null,
        gold: null,
        state: null,
        goldDay: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加机器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMachine(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改机器";
      });
    },
    cancelState() {
      this.openState = false;
      this.resetState();
    },
    resetState() {
      this.formState = {
        machineIds: undefined,
        userId: undefined,
        userName: undefined,
        state: '0',
      };
      this.resetForm("formState");
    },
    handleUpdateStatus() {
      this.resetState();
      if (this.ids && this.ids.length > 0) {
        this.formState.machineIds = this.ids;
        this.openState = true
      } else if (this.queryParams.userName && String(this.queryParams.userName || '').length > 0 && this.machineList && this.machineList.length > 0) {
        let index = this.machineList.findIndex(item => !!item.userId);
        if (index !== -1) {
          this.formState.userId = this.machineList[index].userId;
          this.formState.userName = this.machineList[index].userName;
          this.openState = true
        }
      }
    },
    submitFormState() {
      this.$refs["formState"].validate(valid => {
        if (valid) {
          updateMachineState(this.formState).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.openState = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMachine(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMachine(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除机器编号为"' + ids + '"的数据项？').then(function() {
        return delMachine(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/machine/export', {
        ...this.queryParams
      }, `machine_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
